package com.elite.ffmpegshell;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.concentus.OpusDecoder;
import org.gagravarr.ogg.OggFile;
import org.gagravarr.opus.OpusAudioData;
import org.gagravarr.opus.OpusFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class OpusUtils {
    private static final Log log = LogFactory.getLog(OpusUtils.class);

    public static Integer getOpusDuration(String pathUrl) throws Exception {
        FileInputStream fs = new FileInputStream(new File(pathUrl));
        OggFile ogg = new OggFile(fs);
        OpusFile of = new OpusFile(ogg);
        OpusAudioData ad = null;
        log.debug("rate:" + of.getInfo().getSampleRate());
        OpusDecoder decoder = new OpusDecoder(of.getInfo().getSampleRate(), of.getInfo().getNumChannels());
        byte[] data_packet = new byte[of.getInfo().getSampleRate()];
        int samples = 0;
        while ((ad = of.getNextAudioPacket()) != null) {
            // NOTE: samplesDecoded 是decode出来的short个数，byte需要*2
            int samplesDecoded = decoder.decode(ad.getData(), 0, ad.getData().length, data_packet, 0, of.getInfo().getSampleRate(), false);
            samples += samplesDecoded;
        }
        log.debug("duration:" + samples / of.getInfo().getSampleRate());
        int duration = samples / of.getInfo().getSampleRate();
        return duration;
    }



    public static Integer getOpusDurationURL(String fileUrl) throws Exception {
        URL source = new URL(fileUrl);
        InputStream fs = source.openStream();
        OggFile ogg = new OggFile(fs);
        OpusFile of = new OpusFile(ogg);
        OpusAudioData ad = null;
        log.debug("rate:" + of.getInfo().getSampleRate());
        OpusDecoder decoder = new OpusDecoder(of.getInfo().getSampleRate(), of.getInfo().getNumChannels());
        byte[] data_packet = new byte[of.getInfo().getSampleRate()];
        int samples = 0;
        while ((ad = of.getNextAudioPacket()) != null) {
            // NOTE: samplesDecoded 是decode出来的short个数，byte需要*2
            int samplesDecoded = decoder.decode(ad.getData(), 0, ad.getData().length, data_packet, 0, of.getInfo().getSampleRate(), false);
            samples += samplesDecoded;
        }
        log.debug("duration:" + samples / of.getInfo().getSampleRate());
        int duration = samples / of.getInfo().getSampleRate();
        return duration;
    }
}